//
//  BaseDataPack.m
//  TCPDemo
//
//  Created by bolin on 15-4-6.
//  Copyright (c) 2015年 com.chuzhong. All rights reserved.
//

#import "BLEBaseDataPack.h"
#define QD_BLE_SEND_MAX_LEN  20  //支持的最大发送包大小

@interface BLEBaseDataPack (){
    
    NSInteger _currentIndex;
}

@end


@implementation BLEBaseDataPack

- (id)init{

    if (self=[super init]) {
        
        _currentIndex=0;
        self.isFinished=NO;
    }
    return self;
}

/**
 *  初始化
 *
 *  @param msgData 要发送的蓝牙数据
 *
 *  @return
 */
- (id)initWithData:(NSData *)msgData{

    if (self=[super init]) {
        _currentIndex=0;
        self.isFinished=NO;
        self.sendData=msgData;
    }
    return self;
}

/**
 *  取得分段发送的数据
 *
 *  @return
 */
- (NSData *)beginSendData{
    
    if (self.isFinished) {
        return nil;
    }
    
    if (self.sendData==nil||[self.sendData length]==0) {
        self.isFinished=YES;
        return nil;
    }

    NSString *rangeStr=nil;
    NSData *subData=nil;
    
    // 预加 最大包长度，如果依然小于总数据长度，可以取最大包数据大小
    if ((_currentIndex + QD_BLE_SEND_MAX_LEN) < [self.sendData length]) {
        rangeStr = [NSString stringWithFormat:@"%li,%i", (long)_currentIndex, QD_BLE_SEND_MAX_LEN];
        subData = [self.sendData subdataWithRange:NSRangeFromString(rangeStr)];
        _currentIndex += QD_BLE_SEND_MAX_LEN;
    }
    else {
        rangeStr = [NSString stringWithFormat:@"%li,%i", (long)_currentIndex, (int)([self.sendData length] - _currentIndex)];
        subData = [self.sendData subdataWithRange:NSRangeFromString(rangeStr)];
        _currentIndex += QD_BLE_SEND_MAX_LEN;
        self.isFinished=YES;
    }
    return subData;
}
@end
